const express = require("express");
const router = express.Router();
const { Article } = require("../../models");
const { Op } = require("sequelize");
const { success, failure } = require("../../utils/responses");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");

/**
 * 查询所有文章信息
 * GTE  /articles/
 */
router.get("/", async function (req, res, next) {
  // 查询所有数据
  try {
    // 获取分页参数
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    // 模糊查询
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }
    // 分页查询
    const { count, rows } = await Article.findAndCountAll(condition);
    // 返回
    success(res, "文章查询成功", {
      articles: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询文章详情
 * GET /articles/:id
 */
router.get("/:id", async function (req, res, next) {
  try {
    const article = await getArticle(req);
    success(res, "查询文章成功", { article });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 新增文章
 * POST /articles
 */
router.post("/", async function (req, res, next) {
  try {
    const body = filterBody(req);
    const article = await Article.create(body);
    success(res, "创建文章成功", { article }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除文章
 * DELETE /articles/:id
 */
router.delete("/:id", async function (req, res, next) {
  try {
    const article = await getArticle(req);
    await article.destroy();
    success(res, "删除文章成功");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新文章
 * PUT /articles/:id
 */
router.put("/:id", async function (req, res, next) {
  try {
    const article = await getArticle(req);
    const body = filterBody(req);
    await article.update(body); //删除
    success(res, "更新文章成功", { article });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 获取当前文章
 * @param req
 * @returns {Promise<Model<any, TModelAttributes>>}
 */
async function getArticle(req) {
  const { id } = req.params; //获取文章ID
  // 获取当前文章
  const article = await Article.findByPk(id);
  if (!article) {
    throw new NotFoundError(`ID: ${id} not found`);
  }
  return article;
}

/**
 * 公共方法过滤白名单
 * @param req
 * @returns {{title, content: (string|string|DocumentFragment|*)}}
 */
function filterBody(req) {
  return {
    title: req.body.title,
    content: req.body.content,
  };
}

module.exports = router;
